package com.intelligent.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.intelligent.pojo.Unit;
import com.intelligent.service.UnitService;
import com.intelligent.utils.Result;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * 单位管理接口
 */
@RestController
@RequestMapping("/unit")
public class UnitController {

	@Resource
	private UnitService unitService;

	/**
	 * 分页查询单位
	 */
	@GetMapping("/page")
	public Result<IPage<Unit>> page(@RequestParam(defaultValue = "1") long pageNo,
	                               @RequestParam(defaultValue = "10") long pageSize,
	                               @RequestParam(required = false) String unitCode,
	                               @RequestParam(required = false) String unitName,
	                               @RequestParam(required = false) Integer status) {
		Page<Unit> page = new Page<>(pageNo, pageSize);
		IPage<Unit> result = unitService.pageUnit(page, unitCode, unitName, status);
		return Result.success(result);
	}

	/**
	 * 新增单位（未提供编码则自动生成）
	 */
	@PostMapping("/add")
	public Result<Boolean> create(@RequestBody Unit unit) {
		boolean ok = unitService.createUnit(unit);
		return ok ? Result.success(true) : Result.error("新增单位失败");
	}

	/**
	 * 修改单位
	 */
	@PutMapping("/update")
	public Result<Boolean> update(@RequestBody Unit unit) {
		boolean ok = unitService.updateUnit(unit);
		return ok ? Result.success(true) : Result.error("修改单位失败");
	}

	/**
	 * 根据ID查询
	 */
	@GetMapping("/{id}")
	public Result<Unit> getById(@PathVariable("id") Long id) {
		Unit unit = unitService.selectUnitById(id);
		return unit != null ? Result.success(unit) : Result.error("未找到单位");
	}

	/**
	 * 根据ID删除
	 */
	@DeleteMapping("/{id}")
	public Result<Boolean> delete(@PathVariable("id") Long id) {
		boolean ok = unitService.deleteUnit(id);
		return ok ? Result.success(true) : Result.error("删除单位失败");
	}
} 